package server.controller;

import java.util.Iterator;

import shared.messages.CoordMessage;
import shared.messages.StartMessage;
import shared.messages.WinMessage;

/**
 * The Class Broadcaster
 * - used to broadcast messages to clients.
 */
public class Broadcaster extends Thread {
	
	/** The active sessions object containing clientSessions list. */
	private ActiveSessions activeSessions;
	
	/** Contains outbound messages. */
	private OutboundMessages outQueue;

	/**
	 * Instantiates a new broadcaster.
	 *
	 * @param activeSessions the ActiveSessions object
	 * @param outQueue the OutboundMessages object
	 */
	public Broadcaster(ActiveSessions activeSessions, OutboundMessages outQueue) {
		this.activeSessions = activeSessions;
		this.outQueue = outQueue;
		start();
	}


	/**Gets the first outbound message and sends it to specified clients
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		while (true) {
			Object msg = outQueue.getMessage();

			synchronized (activeSessions) {
				Iterator<ClientSession> itr = activeSessions.iterator();

				while (itr.hasNext()) {
					ClientSession cli = itr.next();

					if (!cli.isAlive()) {
						itr.remove();
					} else if (msg == null) {
						continue;
					} else {
						if (msg instanceof StartMessage) {
							if (cli.p.gameId == ((StartMessage) msg).gameId) {
								cli.sendMessage((StartMessage) msg);
							}
						} else if (msg instanceof CoordMessage) {
							if (cli.p.gameId == ((CoordMessage) msg).gameId) {
								cli.sendMessage((CoordMessage) msg);
							}
						} else if (msg instanceof WinMessage) {
							if (cli.p.gameId == ((WinMessage) msg).gameId) {
								cli.sendMessage((WinMessage) msg);
							}
						}
					}
				}
			}
		}
	}
}